dfs and similar dp graphs trees *1300

Please click on ads to support us..

Python Code:

from sys import *
setrecursionlimit(10 ** 8)
for i in range(int(input())):
	n = int(input())
	a = list(map(int,input().split()))
	graph =  [[] for i in range(n+1)]
	for i in range(2 , n+1):
		graph[i].append(a[i-2])
		graph[a[i-2]].append(i)
	b = input()
	b = b.replace('W' , '1')
	b = b.replace('B' , '0')
	b = [-1] + list(map(int,b))
	dp = [[0 , 0] for i in range(n+1)]
	vis = [0 for i in range(n+1)]
	def dfs(u):
		vis[u] = 1
		dp[u][b[u]] = 1
		for v in graph[u]:
			if vis[v] == 0:
				dfs(v)
				dp[u][0] += dp[v][0]
				dp[u][1] += dp[v][1]
	def main():
		dfs(1)
		count = 0
		for i in dp[1:]:
			if i[0] == i[1]:
				count += 1
		print(count)
	main()

C++ Code:

/* Author: Abhishek Singh */
#include <bits/stdc++.h>
typedef long long ll;
#define mod 1e9+7;
#define int long long int 
using namespace std;
#define nl cout<<"\n";
#define setBits(x) __builtin_popcountll(x)
const int INF=1e9;
vector <int> storePrime;bool primeSieve[10000001];
void sieve(){primeSieve[0]=true;primeSieve[1]=true;int limit=10000000;for(int i=2;i*i<=limit;i++)
{if(!primeSieve[i]){for(int j=i*i;j<=limit;j+=i)primeSieve[j]=true;}}for(int i=2;i<=limit;i++)
{if(!primeSieve[i]) storePrime.push_back(i);}}
void swap(ll &x,ll &y){ll temp=x;x=y;y=temp;}
ll factors(ll n){ll c=0;for(int j=1;j*j<=n;j++){if(n%j==0&&n!=j*j)c+=2;else if(n%j==0&&n==j*j)c++;}return c;}
/***********************************************************************************************************/
int dfs(int root,vector<int> adj[],string s,int &count){
	int ans=0;
	if(s[root-1]=='B')
		ans++;
	else
		ans--;
	for(auto i:adj[root]){
		ans=ans+dfs(i,adj,s,count);
	}
	count+=ans==0;
	return ans;
}
void solve(){
	int n;
	cin>>n;
	vector<int> a(n);int root=0;
	for(int i=0;i<n-1;i++)cin>>a[i];
	string s;cin>>s;
	vector<int> adj[n+1];
	for(int i=0;i<n-1;i++){
		adj[a[i]].push_back(i+2);
	}
	int count=0;
	dfs(1,adj,s,count);
	cout<<count;nl;
}
int32_t main(){
	ios::sync_with_stdio(0);
	cin.tie(NULL);cout.tie(NULL);
	#ifndef ONLINE_JUDGE
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
	#endif
 
	int t = 1;
	cin>>t;
	//sieve();
	while(t--)solve();
	return 0;
}


Comments

Submit
0 Comments
More Questions

343B - Alternating Current
758B - Blown Garland
1681B - Card Trick
1592A - Gamer Hemose
493D - Vasya and Chess
1485A - Add and Divide
337B - Routine Problem
1392D - Omkar and Bed Wars
76E - Points
762C - Two strings
802M - April Fools' Problem (easy)
577B - Modulo Sum
1555B - Two Tables
1686A - Everything Everywhere All But One
1469B - Red and Blue
1257B - Magic Stick
18C - Stripe
1203B - Equal Rectangles
1536A - Omkar and Bad Story
1509A - Average Height
1506C - Double-ended Strings
340A - The Wall
377A - Maze
500A - New Year Transportation
908D - New Year and Arbitrary Arrangement
199A - Hexadecimal's theorem
519C - A and B and Team Training
631A - Interview
961B - Lecture Sleep
522A - Reposts